package com.haoxuer.discover.filter.base;

import com.haoxuer.discover.filter.common.Filter;
import com.haoxuer.discover.filter.common.FilterChain;
import com.haoxuer.discover.filter.common.HandlerRequest;
import com.haoxuer.discover.filter.common.HandlerResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class MockFilterChain implements FilterChain {


  private final List<Filter> filters;

  private Iterator<Filter> iterator;

  public void addFilter(Filter filter) {
    this.filters.add(filter);
  }


  public MockFilterChain(Filter... filters) {
    this.filters = new ArrayList<>();
    if (filters != null) {
      for (Filter filter : filters) {
        this.filters.add(filter);
      }
    }
  }

  private static List<Filter> initFilterList(Filter... filters) {
    return Arrays.asList(filters);
  }

  @Override
  public void doFilter(HandlerRequest request, HandlerResponse response) {
    if (this.iterator == null) {
      this.iterator = this.filters.iterator();
    }

    if (this.iterator.hasNext()) {
      Filter nextFilter = (Filter) this.iterator.next();
      nextFilter.doFilter(request, response, this);
    }
  }
}
